import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_syt/domain/widgets/photo_views_more_screen.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/fade_route.dart';
import 'package:flutter_syt/utils/image_picker_helper.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';

class ImageUpload extends StatefulWidget {
  final List<File> images;

  final double width;

  final double height;

  final Function(List<File>) onChange;
  final int maxLength;

  ImageUpload({
    this.images = const <File>[],
    this.width = 74,
    this.height = 60,
    required this.onChange,
    this.maxLength = 9,
  });

  @override
  _ImageUploadState createState() => _ImageUploadState();
}

class _ImageUploadState extends State<ImageUpload> {
  ChooseImageData? _images;

  // initialize() {}

  @override
  void initState() {
    // this.initialize();
    super.initState();
  }

  @override
  void didUpdateWidget(ImageUpload oldWidget) {
    // this.initialize();
    super.didUpdateWidget(oldWidget);
  }

  var chooseIndex = -1;
  Future<ChooseImageData> _pickImage() async {
    FocusScope.of(context).requestFocus(FocusNode());
    int index =1;
    // int index = await DialogHelper.showBottom(context);
    // if (index == 2) {
    //   return ChooseImageData([]);
    // }
    chooseIndex = index;
    return await ImageHelper.pickMutableImage(context,
        source: index, maxCount: widget.maxLength, selected: _images?.entities);
  }

  _uploadImage() async {
    try {
      var picked = await _pickImage();

      if (picked.files.isEmpty) {
        return;
      }
      if (chooseIndex == 0) {
        if (_images != null) {
          try {
            _images?.files.addAll(picked.files);
            var data = picked.entities?.first;
            if (data != null) {
              _images?.entities?.add(data);
            }
          } catch (e) {
            _images = picked;
          }
        } else {
          _images = picked;
        }
      } else {
        _images = picked;
      }

      if (_images != null) {
        try {
          var files = _images?.files ?? [];
          // widget.onChange(files);
          widget.onChange.call(files);
        } catch (e) {
          widget.onChange.call(picked.files);
        }
      } else {
        widget.onChange.call(picked.files);
      }
      if (mounted) {
        setState(() {});
      }
    } catch (e) {
      // debugPrint(e);
    }
  }

  /// 上传按钮
  Widget _uploadBtn() {
    return Container(
      width: widget.width + 15,
      height: widget.height + 15,
      alignment: Alignment.bottomLeft,
      child: GestureDetector(
        child: ImageItemWrapper(
          width: widget.width,
          height: widget.height,
          child: const Icon(
            Icons.add,
            color: Color(0xFF979797),
            size: 40,
          ),
        ),
        onTap: () {
          _uploadImage();
        },
      ),
    );
  }

  Widget renderImageItem(File image, int index, List<File> images) {
    return Container(
      child: Stack(
        // overflow: Overflow.visible,
        children: [
          Container(
            width: widget.width + 15,
            height: widget.height + 15,
            alignment: Alignment.bottomLeft,
            child: ImageItem(
              image: image,
              index: index,
              fileRows: images,
              width: widget.width,
              height: widget.height,
            ),
          ),
          Positioned(
            top: 0,
            right: 0,
            child: IconButton(
              padding: EdgeInsets.all(4),
              alignment: Alignment.center,
              constraints: BoxConstraints(
                minWidth: 30,
                minHeight: 30,
              ),
              icon: Icon(
                Icons.remove_circle,
                size: 24.0,
                color: Color(0xFFF57575),
              ),
              onPressed: ClickUtils.debounce(() {
                setState(() {
                  try {
                    _images?.files.removeAt(index);
                    _images?.entities?.removeAt(index);
                  } catch (e) {}
                });
                widget.onChange(_images?.files ??[]);
              }),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    var image = _images?.files ?? [];
    return Container(
      child: Wrap(
        spacing: 0,
        runSpacing: 0,
        children: [
          ...image
              .asMap()
              .map((i, e) => MapEntry(i, renderImageItem(e, i, image)))
              .values
              .toList(),
          if (image.length < widget.maxLength) _uploadBtn(),
        ],
      ),
    );
  }
}

class ImageItemWrapper extends StatelessWidget {
  final Widget? child;
  final double? width;
  final double? height;

  ImageItemWrapper({
    this.child,
    this.width,
    this.height,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: this.width,
      height: this.height,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        border: Border.all(
          color: ThemeColor.colorBlack60,
          width: 0.5,
        ),
        borderRadius: const BorderRadius.all(
          Radius.circular(8.0),
        ),
      ),
      child: child,
    );
  }
}

class ImageItem extends StatefulWidget {
  final File image;

  final List<File> fileRows;

  final double? width;

  final double? height;

  final int index;

  ImageItem({
    required this.index,
    required this.image,
    required this.fileRows,
    this.width,
    this.height,
  });

  @override
  _ImageItemState createState() => _ImageItemState();
}

class _ImageItemState extends State<ImageItem> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Container(
          color: Colors.white,
          child: Image.file(
            widget.image,
            width: widget.width,
            height: widget.height,
            fit: BoxFit.cover,
          ),
        ),
      ),
      onTap: ClickUtils.debounce(() {
        Navigator.of(context).push(
          FadeRoute(
              page: PhotoViewMoreScreen(
                  imageRows: [],
                  fileRows: widget.fileRows,
                  defaultImage: widget.index
                  // imageProvider: FileImage(widget.image
                  )),
        );
      }),
    );
  }
}
